package com.wang.weather.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wang.weather.Utils.ResData;
import com.wang.weather.entity.Address;
import com.wang.weather.entity.UserLike;
import com.wang.weather.mapper.AddressMapper;
import com.wang.weather.mapper.LikeMapper;
import com.wang.weather.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private LikeMapper likeMapper;
    @Override
    public ResData getAddress() {
        List<Address> addresses = addressMapper.selectList(null);
        return ResData.resultObject(addresses);
    }

    //删除地区
    @Override
    @Transactional
    public ResData delAddress(String id) {
        //判断是否被喜欢
        Address address = addressMapper.selectById(id);
        String name = address.getAddress();

        LambdaQueryWrapper<UserLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLike::getAddress,name);
        List<UserLike> userLikes = likeMapper.selectList(queryWrapper);
        if (userLikes.size()>0){
            int delete = likeMapper.delete(queryWrapper);
        }


        int i = addressMapper.deleteById(id);
        return ResData.resultInt(i);
    }

    @Override
    public ResData putAddress(Address address) {
        int i = addressMapper.updateById(address);
        return ResData.resultInt(i);
    }

    //增加地区
    @Override
    public ResData addAddress(Address address) {
        //判断是否已经存在
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getAddress,address.getAddress());
        if (addressMapper.selectList(queryWrapper).size()>0){
            throw new RuntimeException("该地区已经存在");
        }
        int insert = addressMapper.insert(address);
        return ResData.resultInt(insert);
    }
}
